package net.zhnb.controller;

import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.zhnb.bean.Ad;
import net.zhnb.bean.AdKey;
import net.zhnb.bean.Global;
import net.zhnb.bean.GlobalKey;
import net.zhnb.bean.LotteryKey;
import net.zhnb.bean.Room;
import net.zhnb.bean.RoomKey;
import net.zhnb.bean.Shower;
import net.zhnb.bean.ShowerKey;
import net.zhnb.bean.Tag;
import net.zhnb.bean.TagKey;
import net.zhnb.service.AdService;
import net.zhnb.service.GlobalService;
import net.zhnb.service.LotteryService;
import net.zhnb.service.RoomService;
import net.zhnb.service.ShowerService;
import net.zhnb.service.TagService;
import net.zhnb.util.Constants;
import net.zhnb.util.ProjectUtil;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import finaler.util.Page;
import finaler.util.PageList;

@Controller
@RequestMapping("admin")
public class AdminController {

	@Resource
	private RoomService roomService;

	@Resource
	private ShowerService showerService;

	@Resource
	private TagService tagService;

	@Resource
	private GlobalService globalService;

	@Resource
	private AdService adService;

	@Resource
	private LotteryService lotteryService;
	
	@RequestMapping()
	public String index() {
		return "/admin/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request) {
		if (request.getParameter("adminname").equalsIgnoreCase("weikao")
				&& request.getParameter("adminpsw").equalsIgnoreCase("06922")) {
			request.getSession().setAttribute(Constants.ADMIN_SESSION_KEY,
					"admin");
			return "redirect:/admin/menu";
		} else {
			return "redirect:/admin";
		}
	}

	@RequestMapping(value = "/menu")
	public String menu() {
		return "/admin/menu";
	}

	@RequestMapping(value = "/quit")
	public String quit(HttpServletRequest request) {
		request.getSession().setAttribute(Constants.ADMIN_SESSION_KEY, null);
		return "redirect:/admin";
	}

	@RequestMapping("/systemManage")
	public String systemManage(HttpServletRequest request) throws Exception {
		Global global = globalService.findByKey(new GlobalKey(new BigDecimal(
				"1")));
		request.setAttribute("global", global);
		return "/admin/systemManage";
	}

	@RequestMapping("/systemModi")
	public String systemModi(HttpServletRequest request) throws Exception {
		Global global = new Global();
		global.setId(new BigDecimal(request.getParameter("id")));
		global.setLotterynum(new BigDecimal(request.getParameter("lotterynum").equals("") ? "0" : request.getParameter("lotterynum")));
		global.setLotterypersent1(new BigDecimal(request.getParameter("lotterypersent1").equals("") ? "0" : request.getParameter("lotterypersent1")));
		global.setLotterypersent2(new BigDecimal(request.getParameter("lotterypersent2").equals("") ? "0" : request.getParameter("lotterypersent2")));
		global.setLotterypersent3(new BigDecimal(request.getParameter("lotterypersent3").equals("") ? "0" : request.getParameter("lotterypersent3")));
		global.setLotterylun(new BigDecimal(request.getParameter("lotterylun").equals("") ? "0" : request.getParameter("lotterylun")));
		global.setSystemweibo(request.getParameter("systemweibo"));
		globalService.update(global);
		return "redirect:/admin/menu";
	}

	@RequestMapping("/roomManage")
	public String roomManage(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(20);
		PageList roomList = roomService.getPageList(page);
		request.setAttribute("roomList", roomList);
		return "/admin/roomManage";
	}

	@RequestMapping(value = "/roomAdd", method = RequestMethod.POST)
	public String roomAdd(HttpServletRequest request) throws Exception {
		Room room = new Room();
		room.setRoomname(request.getParameter("roomname"));
		room.setRoomaddress(request.getParameter("roomaddress") == null ? ""
				: request.getParameter("roomaddress"));
		room.setRoomtel(request.getParameter("roomtel") == null ? "" : request
				.getParameter("roomtel"));
		roomService.insert(room);
		return "redirect:/admin/roomManage";
	}

	@RequestMapping(value = "/roomDel_{roomId}")
	public String roomDel(@PathVariable BigDecimal roomId) throws Exception {
		roomService.deleteByKey(new RoomKey(roomId));
		return "redirect:/admin/roomManage";
	}

	@RequestMapping(value = "/roomModi_{roomId}")
	public String roomModi(@PathVariable BigDecimal roomId,
			HttpServletRequest request) throws Exception {
		Room room = roomService.findByKey(new RoomKey(roomId));
		request.setAttribute("room", room);
		showerService.deleteByRoomId(roomId);
		return "/admin/roomModify";
	}

	@RequestMapping(value = "/roomModi")
	public String roomModiSave(HttpServletRequest request) throws Exception {
		Room room = new Room();
		room.setId(new BigDecimal(request.getParameter("id")));
		room.setRoomname(request.getParameter("roomname"));
		room.setRoomaddress(request.getParameter("roomaddress") == null ? ""
				: request.getParameter("roomaddress"));
		room.setRoomtel(request.getParameter("roomtel") == null ? "" : request
				.getParameter("roomtel"));
		roomService.update(room);
		return "redirect:/admin/roomManage";
	}

	@RequestMapping("/showerManage")
	public String showerManage(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(20);
		PageList showerList = showerService.getPageList(page);
		request.setAttribute("showerList", showerList);
		List<Room> roomList = roomService.findAll();
		request.setAttribute("roomList", roomList);
		return "/admin/showerManage";
	}

	@RequestMapping(value = "/showerAdd", method = RequestMethod.POST)
	public String showerAdd(HttpServletRequest request) throws Exception {
		Shower shower = new Shower();
		shower.setShowername(request.getParameter("showername"));
		shower.setRoomId(new BigDecimal(request.getParameter("roomid")));
		showerService.insert(shower);
		return "redirect:/admin/showerManage";
	}

	@RequestMapping(value = "/showerDel_{showerId}")
	public String showerDel(@PathVariable BigDecimal showerId) throws Exception {
		showerService.deleteByKey(new ShowerKey(showerId));
		tagService.deleteByShowerId(showerId);
		return "redirect:/admin/showerManage";
	}

	@RequestMapping(value = "/showerModi_{showerId}")
	public String showerModi(@PathVariable BigDecimal showerId,
			HttpServletRequest request) throws Exception {
		Shower shower = showerService.findByKey(new ShowerKey(showerId));
		request.setAttribute("shower", shower);
		List<Room> roomList = roomService.findAll();
		request.setAttribute("roomList", roomList);
		return "/admin/showerModify";
	}

	@RequestMapping(value = "/showerModi")
	public String showerModiSave(HttpServletRequest request) throws Exception {
		Shower shower = new Shower();
		shower.setId(new BigDecimal(request.getParameter("id")));
		shower.setShowername(request.getParameter("showername"));
		shower.setRoomId(new BigDecimal(request.getParameter("roomid")));
		showerService.update(shower);
		return "redirect:/admin/showerManage";
	}

	@RequestMapping("/tagManage")
	public String tagManage(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(50);
		PageList tagList = tagService.getPageList(page);
		request.setAttribute("tagList", tagList);

		page.setRange(2000);
		PageList showerList = showerService.getPageList(page);
		request.setAttribute("showerList", showerList);

		Global global = globalService.findByKey(new GlobalKey(new BigDecimal(
				"1")));
		request.setAttribute("global", global);

		request.setAttribute("q_showerid", request.getParameter("showerid"));
		request.setAttribute("q_lotterylun", request.getParameter("lotterylun"));
		request.setAttribute("q_type", request.getParameter("type"));

		return "/admin/tagManage";
	}

	@RequestMapping(value = "/tagAdd", method = RequestMethod.POST)
	public String tagAdd(HttpServletRequest request) throws Exception {
		Tag tag = new Tag();
		tag.setShowerId(new BigDecimal(request.getParameter("showerid")));
		tag.setType(new BigDecimal(request.getParameter("type")));
		tag.setLotterylun(new BigDecimal(request.getParameter("lotterylun")));
		tagService.insert(tag);
		return "redirect:/admin/tagManage?showerid="
				+ request.getParameter("showerid") + "&type="
				+ request.getParameter("type") + "&lotterylun="
				+ request.getParameter("lotterylun");
	}

	@RequestMapping(value = "/tagDel_{tagId}")
	public String tagDel(@PathVariable BigDecimal tagId) throws Exception {
		tagService.deleteByKey(new TagKey(tagId));
		return "redirect:/admin/tagManage";
	}

	@RequestMapping(value = "/tagDownload")
	public void tagDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		Page page = new Page(request);
		page.setRange(2000);
		PageList tagList = tagService.getPageList(page);
		List<?> list = tagList.getList();

		StringBuffer csvBuf = new StringBuffer();
		csvBuf.append("场馆,展位,类型,第几轮,url" + "\r\n");

		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> tag = (HashMap<String, Object>) list.get(i);
			csvBuf.append(tag.get("roomname") + ",");
			csvBuf.append(tag.get("showername") + ",");
			csvBuf.append(tag.get("type").equals(0) ? "NFC," : "QR,");
			csvBuf.append("第" + tag.get("lotterylun") + "轮,");
			csvBuf.append(Constants.URL+ "/main/tag_"+ ProjectUtil.encodeBase64(Constants.CODE_NAME + "_"+ tag.get("id") + "_" + Constants.CODE_NAME));
			csvBuf.append("\r\n");
		}
		OutputStream os = response.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");// 指定字符集，解决内容乱码
		try {
			response.reset();// 增加这句,可解决IE中无法下载文件，但在Chrome中正常的问题
			response.setContentType("text/csv; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename="+ new String("标签制作清单.csv".getBytes("gb2312"), "ISO8859-1"));
			osw.write('\ufeff');// BOM防乱码
			osw.write(csvBuf.toString());
			osw.flush();
		} finally {
			osw.close();
			os.close();
		}
	}

	@RequestMapping("/adManage")
	public String adManage(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(50);
		PageList adList = adService.getPageList(page);
		request.setAttribute("adList", adList);
		return "/admin/adManage";
	}
	
	
	@RequestMapping("/showerUpload")
	public String showerUpload(MultipartHttpServletRequest multipartRequest) throws Exception {
		String showerid = multipartRequest.getParameter("showerid");
		MultipartFile multipartFile = multipartRequest.getFile("adimg");
		String filename = multipartFile.getOriginalFilename();
		String imgtype = filename.substring(filename.lastIndexOf("."));
		String ctxPath = multipartRequest.getSession().getServletContext().getRealPath("/") + "upload/shower/";
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()){
			dirPath.mkdir();
		}
		String newFileName = ProjectUtil.getCurrentFormatStr("yyyy-MM-dd-HH-mm-ss-")+ new Random().nextInt(9999)  + imgtype;
		File uploadFile = new File(ctxPath + newFileName);
		FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);
		Shower shower = new Shower();
		shower.setId(new BigDecimal(showerid));
		shower.setShoweradimg(newFileName);
		showerService.update(shower);
		return "redirect:/admin/showerManage";
	}
	
	
	@RequestMapping("/adUpload")
	public String adUpload(MultipartHttpServletRequest multipartRequest) throws Exception {
		MultipartFile multipartFile = multipartRequest.getFile("adimg");
		String filename = multipartFile.getOriginalFilename();
		String imgtype = filename.substring(filename.lastIndexOf("."));
		String ctxPath = multipartRequest.getSession().getServletContext().getRealPath("/") + "upload/ad/";
		File dirPath = new File(ctxPath);
		if (!dirPath.exists()){
			dirPath.mkdir();
		}
		String newFileName = ProjectUtil.getCurrentFormatStr("yyyy-MM-dd-HH-mm-ss-")+ new Random().nextInt(9999)  + imgtype;
		File uploadFile = new File(ctxPath + newFileName);
		FileCopyUtils.copy(multipartFile.getBytes(), uploadFile);
		Ad ad = new Ad();
		ad.setImgpath(newFileName);
		ad.setDatetime(ProjectUtil.getCurrentFormatStr("yyyy-MM-dd HH:mm:ss"));
		adService.insert(ad);
		return "redirect:/admin/adManage";
	}
	
	@RequestMapping(value = "/adDel_{adId}")
	public String adDel(@PathVariable BigDecimal adId,HttpServletRequest request) throws Exception {
		Ad ad = adService.findByKey(new AdKey(adId));
		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload/ad/";
		File file = new File(ctxPath+ad.getImgpath());
		if(file.exists()){
			file.delete();
		}
		adService.deleteByKey(new AdKey(adId));
		return "redirect:/admin/adManage";
	}

	@RequestMapping(value = "/adDownload")
	public void adDownload(HttpServletRequest request,HttpServletResponse response) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		Page page = new Page(request);
		page.setRange(2000);
		PageList adList = adService.getPageList(page);
		List<?> list = adList.getList();

		StringBuffer csvBuf = new StringBuffer();

		for (int i = 0; i < list.size(); i++) {
			Ad ad = (Ad) list.get(i);
			csvBuf.append(Constants.URL+ "/main/ad_"+ ProjectUtil.encodeBase64(Constants.AD_NAME + "_"+ ad.getId() + "_" + Constants.AD_NAME));
			csvBuf.append("\r\n");
		}
		OutputStream os = response.getOutputStream();
		OutputStreamWriter osw = new OutputStreamWriter(os, "utf-8");// 指定字符集，解决内容乱码
		try {
			response.reset();// 增加这句,可解决IE中无法下载文件，但在Chrome中正常的问题
			response.setContentType("text/csv; charset=utf-8");
			response.setHeader("Content-Disposition", "attachment;filename="+ new String("智慧展示码制作清单.csv".getBytes("gb2312"), "ISO8859-1"));
			osw.write('\ufeff');// BOM防乱码
			osw.write(csvBuf.toString());
			osw.flush();
		} finally {
			osw.close();
			os.close();
		}
	}
	
	@RequestMapping("/lotteryManage")
	public String lotteryManage(HttpServletRequest request) throws Exception {
		Page page = new Page(request);
		page.setRange(50);
		PageList lotteryList = lotteryService.getPageList(page);
		request.setAttribute("lotteryList", lotteryList);
		return "/admin/lotteryManage";
	}

	@RequestMapping(value = "/lotteryDel_{lotteryId}")
	public String lotteryDel_(@PathVariable BigDecimal lotteryId) throws Exception {
		lotteryService.deleteByKey(new LotteryKey(lotteryId));
		return "redirect:/admin/lotteryManage";
	}

}
